//
//  HDSelectMonthViewController.m
//  CreditGroup
//
//  Created by Mirko on 2017/1/19.
//  Copyright © 2017年 haodai. All rights reserved.
//

#import "HDSelectMonthViewController.h"
#import "HDSelectItemCell.h"
#import <MCPublicModule/MCPMCommonHeader.h>
#import "HDMonthModle.h"
#import "HDMonthControlModle.h"
#import "HDSelectCollectionItemHeader.h"
#import "HDSelectMonthCollectionHeader.h"

static NSString *const kCollectionItemCellIdentifier = @"HDSelectItemCell";
static NSString *const kCollectionItemHeaderIdentifier = @"HDSelectCollectionItemHeader";
const static NSInteger kItemCountEachline = 4;
const static NSInteger kMonthCount = 12;
const static NSInteger kYearsCount = 3;

@interface HDSelectMonthViewController () <UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *monthCollectionView;
@property (nonatomic, strong) NSMutableArray *monthMap;
@property (nonatomic, strong) NSMutableArray *yearMap;

//起始年份
@property (nonatomic, strong) HDMonthModle *start;
@property (nonatomic, strong) HDMonthModle *end;
@property (nonatomic, strong) HDMonthModle *current;

//“选择” 年份月份
@property (nonatomic, strong) HDMonthModle *selectStart;
@property (nonatomic, strong) HDMonthModle *selectEnd;


//点选区间，共三段，取三年；
@property (nonatomic, strong) NSMutableArray *rangs;


@end

@implementation HDSelectMonthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.monthMap = [NSMutableArray new];
    self.yearMap = [NSMutableArray new];
    self.rangs = [NSMutableArray new];
    
    
    [self setupViewController];
    [self setUpTimeData];
    [self calculateData];
    [self createMonthMap];
    
}

#pragma mark member method
-(void) setupViewController
{
    self.title = @"缴纳月份";
    UINib *nib = [UINib nibWithNibName:@"HDSelectItemCell" bundle:nil];
    [self.monthCollectionView registerNib:nib forCellWithReuseIdentifier:kCollectionItemCellIdentifier];
    
    nib = [UINib nibWithNibName:@"HDSelectCollectionItemHeader" bundle:nil];
    [self.monthCollectionView registerNib:nib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kCollectionItemHeaderIdentifier];
    [self setupCollectionHeader];
    self.monthCollectionView.allowsMultipleSelection = YES;
    self.monthCollectionView.backgroundColor = [UIColor colorWithRed:229.f/255 green:229.f/255 blue:229.f/255 alpha:1];
}

-(void) setupCollectionHeader
{
    HDSelectMonthCollectionHeader *header = [[HDSelectMonthCollectionHeader alloc] initWithNote:self.noteString];
    header.frame = CGRectMake(0, -header.bounds.size.height, 375, header.bounds.size.height);
    self.monthCollectionView.contentInset = UIEdgeInsetsMake(header.bounds.size.height, 0, 0, 0);
    [self.monthCollectionView addSubview:header];
}

-(void) createMonthMap
{
    [self createDefaultMap];
    [self significantMontMap];
}

-(void) setUpTimeData
{
    id dsStart = self.timeRange[0];
    id dsEnd = self.timeRange[1];
    
    if ([dsStart isKindOfClass:[NSNumber class]] && [dsEnd isKindOfClass:[NSNumber class]]) {
        self.start = [HDMonthModle modleWithTimeInterval:dsStart];
        self.end = [HDMonthModle modleWithTimeInterval:dsEnd];
    }
    else
    {
        self.start = [HDMonthModle modleWithFullDate:dsStart];
        self.end = [HDMonthModle modleWithFullDate:dsEnd];
    }
}

//@"2017-5", @"2017-10"
-(void) significantMontMap
{
    NSInteger start = self.start.nMonth + [self getYearSection:self.start.year] * kMonthCount;
    NSInteger end = self.end.nMonth + [self getYearSection:self.end.year] * kMonthCount;
    
    NSMutableArray *significantMap = [NSMutableArray new];
    for (int i = 0; i < kYearsCount * kMonthCount; ++i) {
        if ((i >= 0 && i < start - 1) || (i >= end && i < kYearsCount * kMonthCount)) {
            DLOG(@"i = %d, row %ld ,section = %ld", i, i % kMonthCount,i / kMonthCount );
            NSIndexPath *path = [NSIndexPath indexPathForRow:i % kMonthCount inSection:i / kMonthCount];
            [significantMap addObject:path];
        }
    }
    [self setMonthCollectionItem:significantMap withStatus:kStatusUnavail];
}

-(void) setMonthCollectionItem:(NSArray *) monthPositions withStatus:(ECollectionStatus) status
{

    for (NSIndexPath *path in monthPositions) {
        DLOG(@"path = row:%ld, section:%ld", path.row, path.section);
        HDMonthControlModle *modle = self.monthMap[path.section][path.row];
        DLOG(@"control model :%@", modle);
        modle.status = status;
    }
    
    
    DLOG(@"indexPathsForSelectedItems = %ld", self.monthCollectionView.indexPathsForSelectedItems.count);
    

    if (status == kStatusSelected) {
        [UIView performWithoutAnimation:^{
            [self.monthCollectionView reloadItemsAtIndexPaths:monthPositions];
        }];
    }
    
    
    for (NSIndexPath *path in monthPositions) {
        if (status == kStatusSelected) {
            [self.monthCollectionView selectItemAtIndexPath:path animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        }
    }
    
    
    DLOG(@"indexPathsForSelectedItems = %ld", self.monthCollectionView.indexPathsForSelectedItems.count);
    
    DLOG(@"Start: %@ ,End: %@", self.selectStart.dataPara, self.selectEnd.dataPara);
}

-(void) resetSelectCell:(NSIndexPath *) removeIndex
{
    NSMutableArray *selects = [NSMutableArray arrayWithArray:self.monthCollectionView.indexPathsForSelectedItems];
    [selects removeObject:removeIndex];
    for (NSIndexPath *indexPath in selects) {
        HDMonthControlModle *modle = self.monthMap[indexPath.section][indexPath.row];
        DLOG(@"control model :%@", modle);
        modle.status = kStatusDefault;
        modle.flag = kFlageDefault;
        [self.monthCollectionView deselectItemAtIndexPath:indexPath animated:NO];
    }
    [UIView performWithoutAnimation:^{
        [self.monthCollectionView reloadItemsAtIndexPaths:selects];
    }];
}

-(void) createDefaultMap
{
    [self.monthMap removeAllObjects];
    for (int i = 0; i < kYearsCount; i ++) {
        NSMutableArray *eachYear = [NSMutableArray new];
        for ( int j = 0; j < kMonthCount; ++j) {
            HDMonthControlModle *model = [HDMonthControlModle new];
            model.month = [NSString stringWithFormat:@"%d", j + 1];
            model.index = i * kMonthCount + j;
            model.indexPath = [NSIndexPath indexPathForRow:j inSection:i];
            [eachYear addObject:model];
        }
        [self.monthMap addObject:eachYear];
    }
    DLOG(@"%@", self.monthMap);
}

-(void) calculateData
{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-M"];
//    NSDate *data = [NSDate date];
//    NSString *dateStr = [formatter stringFromDate:data];
//    self.current = [HDMonthModle modleWithFullDate:dateStr];
//    for (int i = 0; i < kYearsCount; ++i) {
//        NSInteger year = self.current.nYear - ((kYearsCount - 1) - (i + 1));
//        DLOG(@"%ld", year);
//        [self.yearMap addObject:[NSString stringWithFormat:@"%ld", year]];
//    }
    
    for (int i = 0; i < kYearsCount; ++i) {
        NSInteger year = self.start.nYear + i;
        DLOG(@"%ld", year);
        [self.yearMap addObject:[NSString stringWithFormat:@"%ld", year]];
    }
    
}

-(NSInteger) getYearSection:(NSString *) year
{
    if (![self.yearMap containsObject:year]) {
        return -1;
    }
    
    return [self.yearMap indexOfObject:year];
}

/*
 about select month
 */

-(void) handleSelectAction:(NSIndexPath *) indexPath
{
    NSLog(@"CellData row:%ld section:%ld", indexPath.row, indexPath.section);
    //从新选择
    if (self.selectStart && self.selectEnd)
    {
        self.selectStart = nil;
        self.selectEnd = nil;
        [self resetSelectCell:indexPath];
        HDMonthControlModle *model = self.monthMap[indexPath.section][indexPath.row];
        model.status = kStatusSelected;
        model.flag = kStatusDefault;
        [self.monthCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }
    //第一次选择
    if (!self.selectStart) {
        NSString *year = self.yearMap[indexPath.section];
        NSString *month = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
        self.selectStart = [HDMonthModle modleWithYear:year month:month];
        self.selectStart.idxPath = indexPath;
        HDMonthControlModle *modle = self.monthMap[indexPath.section][indexPath.row];
        modle.status = kStatusSelected;
        modle.flag = kFlagStart;

        [UIView performWithoutAnimation:^{
            [self.monthCollectionView reloadItemsAtIndexPaths:@[indexPath]];
        }];
        [self.monthCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        HDSelectItemCell *cell = (HDSelectItemCell *)[self.monthCollectionView cellForItemAtIndexPath:indexPath];
        [self.monthCollectionView bringSubviewToFront:cell];
        [cell showTips:indexPath];
        
       
    }
    else //第二次选择
    {
        NSString *year = self.yearMap[indexPath.section];
        NSString *month = [NSString stringWithFormat:@"%ld", indexPath.row + 1];
        self.selectEnd = [HDMonthModle modleWithYear:year month:month];
        self.selectEnd.idxPath = indexPath;
        
        HDMonthControlModle *modle = self.monthMap[self.selectEnd.idxPath.section][self.selectEnd.idxPath.row];
        modle.status = kStatusSelected;
        modle.flag = kFlagEnd;
        
        
        if ([self.selectEnd sameAsTime:self.selectStart]) {
            HDSelectItemCell *sCell = (HDSelectItemCell *)[self.monthCollectionView cellForItemAtIndexPath:self.selectStart.idxPath];
            [sCell hiddenTips];
            
            HDSelectItemCell *eCell = (HDSelectItemCell *)[self.monthCollectionView cellForItemAtIndexPath:self.selectEnd.idxPath];
            [eCell hiddenTips];

            DLOG(@"Start: %@ ,End: %@", self.selectStart.dataPara, self.selectEnd.dataPara);
            return;
        }
    
        NSInteger sSection = [self getYearSection:self.selectStart.year];
        NSInteger virtualStart = sSection * kMonthCount + self.selectStart.nMonth;

        NSInteger eSection = [self getYearSection:self.selectEnd.year];
        NSInteger virtualEnd = eSection * kMonthCount + self.selectEnd.nMonth;

        if (virtualEnd < virtualStart) {
            HDMonthModle *temp = nil;
            temp = self.selectStart;
            self.selectStart = self.selectEnd;
            self.selectEnd = temp;
            temp = nil;
            
            ECollectionFlag tempFlag = kFlageDefault;
            
            HDMonthControlModle *sModle = self.monthMap[self.selectStart.idxPath.section][self.selectStart.idxPath.row];
            tempFlag = sModle.flag;
            
            HDMonthControlModle *eModle = self.monthMap[self.selectEnd.idxPath.section][self.selectEnd.idxPath.row];
            
            sModle.flag = eModle.flag;
            eModle.flag = tempFlag;
            
            
            [UIView performWithoutAnimation:^{
                [self.monthCollectionView reloadItemsAtIndexPaths:@[indexPath]];
            }];
            [self.monthCollectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        }
        
        NSInteger start = self.selectStart.nMonth + [self getYearSection:self.selectStart.year] * kMonthCount;
        NSInteger end = self.selectEnd.nMonth + [self getYearSection:self.selectEnd.year] * kMonthCount;
        
        NSMutableArray *significantMap = [NSMutableArray new];
        for (int i = 0; i < kYearsCount * kMonthCount; ++i) {
            if ( i >= start && i < end) {
                DLOG(@"i = %d, row %ld ,section = %ld", i, i % kMonthCount,i / kMonthCount );
                NSIndexPath *path = [NSIndexPath indexPathForRow:i % kMonthCount inSection:i / kMonthCount];
                [significantMap addObject:path];
            }
        }
        [self setMonthCollectionItem:significantMap withStatus:kStatusSelected];
        
        HDSelectItemCell *sCell = (HDSelectItemCell *)[self.monthCollectionView cellForItemAtIndexPath:self.selectStart.idxPath];
        [sCell hiddenTips];
        
        HDSelectItemCell *eCell = (HDSelectItemCell *)[self.monthCollectionView cellForItemAtIndexPath:self.selectEnd.idxPath];
        [eCell hiddenTips];
    }
}

/*
 选择月份结束
 */

-(void) handleSelectCompleteAction
{
    HDSelectedMonth *month = [[HDSelectedMonth alloc] initSelectedMonth:self.selectStart.dataPara endMonth:self.selectEnd.dataPara];
    if (self.block) {
        self.block(month);
    }
}

#pragma mark collection view datasource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return kYearsCount;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return kMonthCount;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HDSelectItemCell *cell = (HDSelectItemCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kCollectionItemCellIdentifier forIndexPath:indexPath];
    
    HDMonthControlModle *modle = self.monthMap[indexPath.section][indexPath.row];
    DLOG(@"%@", modle)
    [cell setCellData:modle];
    
    return cell;
}

- (UICollectionReusableView *)collectionView: (UICollectionView *)collectionView viewForSupplementaryElementOfKind: (NSString *)kind atIndexPath: (NSIndexPath *)indexPath
{
    //Header view 回调，如果footer view size 不设置，不会回调Footer如果要设置Footer 根据Kind判断
    HDSelectCollectionItemHeader *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kCollectionItemHeaderIdentifier forIndexPath:indexPath];
    view.yearLable.text = self.yearMap[indexPath.section];
    return view;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DLOG(@"section %ld, row %ld", indexPath.section, indexPath.row);
    [self handleSelectAction:indexPath];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    [self handleSelectAction:indexPath];
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}


#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DLOG_RECT(@"",self.view.frame);
    DLOG_RECT(@"", self.monthCollectionView.frame);
    //375 / 4 - 1 =  
    CGFloat itemWidth = (collectionView.bounds.size.width / kItemCountEachline) - 1;
    return CGSizeMake(itemWidth, itemWidth);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(ScreenWidth(), 30);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}



//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(ScreenWidth(), 30);
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
